#!/usr/bin/env python
# -*- coding: utf8 -*-

'''
Created on 2011-7-26

京东价格图片识别模块

@author: zhongfeng
'''

import ImageFilter, ImageChops
from captcha_price import *
from j360buy.j360_feature import __360buy_FEATURES_MAP__
import Image
import re
import time

try:
    import psyco
    psyco.full()
except ImportError:
    pass

class CaptchaProfile_360Buy(CaptchaProfile):
    
    def __init__(self):
        pass
    def __new__(cls):
        '''
                    单态实现，初始化一次 
        '''
        if '_inst' not in vars(cls):
            cls.__catagory_FEATURES_MAP__ = dict([(feature_to_data(key),value) for key,value in __360buy_FEATURES_MAP__.iteritems()])
            cls._inst = super(CaptchaProfile_360Buy, cls).__new__(cls)
        return cls._inst

    def filter(self, im):
        return im.filter(ImageFilter.EDGE_ENHANCE_MORE).convert('L').convert('1')

    def split(self, im):
        matrix = {(48,12) : [(15, 3, 21, 11), (23, 3, 25, 11),(27,3,33,11),(35,3,41,11)],
                  (52,12) : [(15, 3, 21, 11), (23, 3, 29, 11),(31,3,33,11),(35,3,41,11),(43,3,49,11)],
                  (65,12) : [(15, 3, 21, 11), (23, 3, 29, 11),(31,3,37,11),(39,3,41,11),(43,3,49,11),(51,3,57,11)],
                  (75,12) : [(15, 3, 21, 11), (23, 3, 29, 11),(31,3,37,11),(39,3,45,11),(47,3,49,11),(51,3,57,11),(59, 3, 65, 11)],
                  (80,12) : [(15, 3, 21, 11), (23, 3, 29, 11),(31,3,37,11),(39,3,45,11),(47,3,53,11),(55,3,57,11),(59, 3, 65, 11),(67,3,73,11)]
                 }
        return [im.crop(box) for box in matrix[im.size]]

    def match(self, im):
        imageData = feature_to_data(CaptchaImageAlgorithm.GetBinaryMap(im))
        result = self.__catagory_FEATURES_MAP__.get(imageData,None)
        if result != None:
            return result
        print CaptchaImageAlgorithm.GetBinaryMap(im)
        source = im.getdata()
        algorithm = CaptchaAlgorithm()
        minimal = min(__360buy_FEATURES_MAP__, key=lambda feature:algorithm.LevenshteinDistance(source, feature_to_data(feature)))
        #print minimal
        return __360buy_FEATURES_MAP__[minimal]

def captcha_360buy(filename):
    return captcha(filename, CaptchaProfile_360Buy())

def test():
    print captcha_360buy(r'c:\gp359329,2.png')

if __name__ == '__main__':
    im = Image.open(r'c:\1.png')
    im2 = Image.open(r'c:\1.png')
    diff = ImageChops.difference(im, im2)
    im = im.filter(ImageFilter.EDGE_ENHANCE_MORE).convert('L').convert('1')
    dt = im.getdata()
    print im.size
    it1 = im.crop((15, 3, 21, 11))
    it2 = im.crop((23, 3, 29, 11))
    it3 = im.crop((31, 3, 37, 11))
    it4 = im.crop((39, 3, 45, 11))
    it5 = im.crop((47, 3, 49, 11))
    it6 = im.crop((51, 3, 57, 11))
    it7 = im.crop((59, 3, 65, 11))
    cia = CaptchaImageAlgorithm()
    s7 = cia.GetBinaryMap(it1)
    print s7
    profile = CaptchaProfile_360Buy()

    print '+++++++++++++++++++++++++++'
    for t in range(100):
        print captcha_360buy(r'c:\5.png')
        
        
